<template>
  <div class="dynamic-container">
    <el-form ref="form" :model="form" label-width="100px">
      <div v-for="(item, index) in configArr" :key="index">
        <el-form-item :label="item.name" v-show="item.show">
          <el-input
            v-if="item.type === 'input' || item.type === 'input-number'"
            :type="item.extra.type"
            :value="form[item.name]"
            @input="handleInput(item.name, $event)"
          ></el-input>
          <el-select
            v-if="item.type === 'select'"
            :value="form[item.name]"
            :placeholder="item.extra.placeholder"
            ref="itemSelect"
            @change="handleSelectItemValue(item.name, $event)"
          >
            <el-option
              v-for="tig in item.extra.options"
              :key="tig.value"
              :label="tig.label"
              :value="tig.value"
            >
            </el-option>
          </el-select>
          <editorCom
            v-if="item.type === 'richText'"
            ref="editorCom"
            :value="form[item.name]"
            :fileSize="500"
            @input="handleeditorComInput(item.name, $event)"
            @giveMediaType="giveMediaTypeeditor"
            :dynamicHeaders="dynamicHeaders"
            :dynamicMethod="dynamicMethod"
            :dynamicUrl="dynamicUrl"
            :ossId="ossId"
          ></editorCom>
          <FileUpload
            v-if="item.type === 'imageUpload'"
            v-model="form[item.extra.displayName]"
            :fileType="item.extra.fileType"
            :url="url"
            @input="getFirelist"
            @deleteFile="deleteFile"
            @giveMediaType="giveMediaType"
            ref="fileUpload"
            :dynamicHeaders="dynamicHeaders"
            :dynamicMethod="dynamicMethod"
            :dynamicUrl="dynamicUrl"
            :ossId="ossId"
            :limit="item.extra.limit"
            :listType="item.extra.listType"
            :who="item.extra.who"
            :drag="true"
          ></FileUpload>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload";
import editorCom from "@/components/Editor";
import { ConfigType } from "@/utils/config-type";
import { postOssUpload } from "@/api/oss";
import { putOssTempUrl } from "@/api/oss";
export default {
  name: "dynamic-form",
  props: {
    allObjectsid: {
      type: Number,
      default: 0,
    },
    type: {
      type: String,
      default: "",
    },
    configFormOld: {
      type: Object,
      default: () => {},
    },
    vrPanoramaArr: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    FileUpload,
    editorCom,
  },
  data() {
    const configData = ConfigType;
    return {
      ConfigType: configData,
      configArr: [],
      form: {},
      url: "",
      ossId: "",
      dynamicHeaders: {},
      dynamicMethod: "PUT",
      dynamicUrl: null,
      uploadParams: {
        path: "map-normal",
        name: "",
        permission: "tenant",
        suffix: "",
        mediaType: "",
        sizeLimit: "",
        attachment: "",
      },
    };
  },
  watch: {
    type: {
      handler(val) {
        this.configArr = this.ConfigType.find(
          (item) => item.name === val
        ).value;
        this.form = {
          allObjectsid: this.allObjectsid,
        };
        this.configArr.map((item) => {
          if (item.name === "vrImageOid") {
            item.extra.options = this.vrPanoramaArr;
          }
          this.$set(this.form, item.name, item.value); // 初始化form中属性对应的值
        });
        // 反显
        setTimeout(() => {
          this.backDisplay();
        }, 200);
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 反显
    backDisplay() {
      if (Object.keys(this.configFormOld).length > 0) {
        const foundKeys = []; // 用于记录在 configArr 中找到的 key
        for (const key in this.configFormOld) {
          if (this.configFormOld.hasOwnProperty(key)) {
            let obj = this.configArr.find((item) => item.name === key);
            if (obj && obj.type === "imageUpload") {
              // 处理图片的反显
              this.$set(this.form, obj.name, []);
              this.$set(this.form, obj.extra.displayName, []); // 初始化存放URL的数组
              if (obj.valueType === "array" && obj.extra.limit >= 1) {
                if (this.configFormOld[obj.name].length > 0) {
                  // 多张图片
                  this.configFormOld[obj.name].map((item) => {
                    this.form[obj.name].push(item); // 存放OSSid
                    this.requeseputOssTempUrl(item, 1, obj.extra.displayName); // 存放URL
                  });
                }
              } else if (obj.valueType === "number" && obj.extra.limit === 1) {
                // 单张图片
                this.form[obj.name].push(this.configFormOld[obj.name]);
                this.requeseputOssTempUrl(
                  this.configFormOld[obj.name],
                  2,
                  obj.extra.displayName
                );
              }
              foundKeys.push(key);
            } else if (obj && obj.type !== "imageUpload") {
              this.$set(this.form, key, this.configFormOld[key]);
              foundKeys.push(key);
            }
          }
        }
        // 处理没在 configArr 中找到的 key  保存原本自带的值例如lastupdate这些属性
        for (const key in this.configFormOld) {
          if (
            this.configFormOld.hasOwnProperty(key) &&
            !foundKeys.includes(key)
          ) {
            this.$set(this.form, key, this.configFormOld[key]);
          }
        }
        this.giveFormtoParent(6);
      }
    },
    requeseputOssTempUrl(ossId, type, name) {
      // console.log(ossId, 11111);
      if (ossId && (typeof ossId === "string" || typeof ossId === "number")) {
        putOssTempUrl(ossId)
          .then((res) => {
            if (res.success) {
              let result = res?.data?.url ?? "";
              if (type === 1) {
                if (this.form[name].length === 0) {
                  this.form[name].push(result);
                } else if (!this.form[name].includes(result)) {
                  this.form[name].push(result);
                }
              } else {
                this.$set(this.form, name, [result]);
              }
            }
          })
          .catch((err) => {});
      }
    },
    giveFormtoParent(ff) {
      this.$emit("giveFormtoParent", this.form);
    },
    handleInput(name, val) {
      // this.$set(this.form, name, val);
      // console.log(this.form, "handleInput");
      this.giveFormtoParent(1);
    },
    handleSelectItemValue(name, val) {
      this.$set(this.form, name, val);
      // console.log(this.form, "handleSelectItemValue");
      this.giveFormtoParent(2);
    },
    handleeditorComInput(name, val) {
      this.$set(this.form, name, val);
      console.log(this.form, "handleeditorComInput");
      this.giveFormtoParent(3);
    },
    getFirelist(data, who) {
      let arr, brr;
      data.forEach((item) => {
        arr = this.form[who];
        if (item.ossId && !arr.includes(item.ossId)) {
          // 已经上传成功的图片反显的时候不带ossId所以得排除
          arr.push(item.ossId);
        }
      });
      this.dynamicHeaders = {};
      this.dynamicMethod = "PUT";
      this.dynamicUrl = null;
      this.ossId = "";
      this.giveFormtoParent(4);
    },
    deleteFile(file, who) {
      let arr, brr;
      arr = this.form[who];
      brr = this.form[who + "url"];
      let index = brr.findIndex((item) => {
        if (typeof item === "object" && Object.keys(item).length > 0) {
          return item.url === file.url;
        } else {
          return item === file.url;
        }
      });
      if (index !== -1) {
        arr.splice(index, 1);
        brr.splice(index, 1);
      }
      this.giveFormtoParent(5);
    },
    giveMediaType(mediaType, who) {
      this.uploadParams.mediaType = mediaType;
      this.uploadParams.suffix = this.uploadParams.mediaType.match(/\/(.+)/)[1];
      this.requestpostOssUpload(who);
    },
    giveMediaTypeeditor(mediaType) {
      this.uploadParams.mediaType = mediaType;
      this.uploadParams.suffix = this.uploadParams.mediaType.match(/\/(.+)/)[1];
      this.requestpostOssUpload("richText");
    },
    requestpostOssUpload(who) {
      if (who === "imageOidList") {
        this.uploadParams.name = "常规图片";
        // this.uploadParams.suffix = "jpg";
      } else if (who === "vrImageOid") {
        this.uploadParams.name = "vr图片";
        // this.uploadParams.suffix = "jpg";
      } else if (who === "richText") {
        this.uploadParams.name = "富文本图片";
      }
      postOssUpload(this.uploadParams)
        .then((res) => {
          if (res.success) {
            this.dynamicHeaders = res.data.headers || {};
            this.dynamicMethod = res.data.method || "PUT";
            this.dynamicUrl = res.data.uploadUrl || "";
            this.ossId = res?.data?.ossId ?? null;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style lang="scss" scoped></style>
